package com.tqz.rocketmq.transaction;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * RocketMQ生产者
 * </p>
 *
 * @author tian
 * @since 2021/2/13 19:55
 */
public class TransactionProducer {

    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, InterruptedException {
        TransactionMQProducer producer = new TransactionMQProducer("tx_producer");
        producer.setNamesrvAddr(Constant.NAME_SERVER_ADDR);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        producer.setExecutorService(executorService);
        producer.setSendMsgTimeout(15000);

        // 本地事物的监听
        producer.setTransactionListener(new TransactionListenerLocal());
        producer.start();

        for (int i = 10; i < 20; i++) {
            String orderId = UUID.randomUUID().toString();
            String body = "{'operation':'doOrder','orderId': '" + orderId + "'}";
            Message message = new Message(Constant.TOPIC, "TagA",
                    orderId, body.getBytes(RemotingHelper.DEFAULT_CHARSET));
            producer.sendMessageInTransaction(message, orderId + "&" + i);
            Thread.sleep(1000);
        }
    }
}
